<template>
    <div style="font-size: 16px">
        <a-space :size="2" class="ml-2">
            <a-tooltip>
                <template #title>刷新数据</template>
                <sysIcon type="system-shuaxin" class="link" style="font-size: 18px; color: #555" @click="props.xGrid.commitProxy('query')"></sysIcon>
            </a-tooltip>
            <vxe-pulldown ref="xGrid2" @hidePanel="closePulldown" destroy-on-close style="position: relative">
                <template #default>
                    <a-tooltip>
                        <template #title>表格设置</template>
                        <sysIcon type="system-shezhi" class="link" style="font-size: 18px; font-weight: bold" @click="xGrid2.togglePanel(), openMorePanel()"></sysIcon>
                    </a-tooltip>
                </template>
                <template #dropdown>
                    <div class="p-2 pt-0 bg-white dark:bg-gery-800" style="width: 300px; box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1); position: absolute; right: 0">
                        <a-tabs v-model:activeKey="activeKey">
                            <a-tab-pane key="1" tab="　列设置　">
                                <vxe-table class="sortable-row-demo" ref="tGrid" auto-resize show-overflow :showHeader="false" :rowConfig="{ height: 38 }" :data="state.tableData" type="checkbox">
                                    <vxe-column field="visible" width="155" title="名称">
                                        <template #default="{ row }">
                                            <a-checkbox :disabled="row.type === 'checkbox' || row.type === 'radio' || row.field === 'operate'" @change="changeTable" v-model:checked="row.visible">{{ row.title ? row.title : '选择' }}</a-checkbox>
                                        </template>
                                    </vxe-column>
                                    <vxe-column field="fixed" width="80" title="固定列">
                                        <template #default="{ row }">
                                            <a-space :size="10" style="font-size: 14px; color: #999">
                                                <a-tooltip>
                                                    <template #title>固定在左侧</template>
                                                    <sysIcon type="system-changyong_fanhui" @click="row.fixed && row.fixed == 'left' ? (row.fixed = undefined) : (row.fixed = 'left'), changeTable()" :class="['cursor-pointer link', row.fixed && row.fixed === 'left' ? 'text-blue-500' : '']" />
                                                </a-tooltip>
                                                <a-tooltip>
                                                    <template #title>固定在右侧</template>
                                                    <sysIcon type="system-changyong_gengduo" @click="row.fixed && row.fixed == 'right' ? (row.fixed = undefined) : (row.fixed = 'right'), changeTable()" :class="['cursor-pointer link', row.fixed && row.fixed === 'right' ? 'text-blue-500' : '']" />
                                                </a-tooltip>
                                            </a-space>
                                        </template>
                                    </vxe-column>
                                    <vxe-column width="45" align="center" field="name" title="排序">
                                        <template #default>
                                            <span class="drag-btn" title="按住进行拖拽排序">
                                                <my-icon style="font-size: 20px; margin-top: 3px" class="cursor-move" type="icon-drag_2"></my-icon>
                                            </span>
                                        </template>
                                    </vxe-column>
                                </vxe-table>
                            </a-tab-pane>
                            <a-tab-pane key="2" tab="表格风格">
                                <div class="flex justify-start items-center p-2 pt-0 pb-3 mt-2">
                                    <span>斑马条纹：</span>
                                    <a-switch v-model:checked="state.tableConfig.stripe" />
                                </div>
                                <a-divider style="margin: 0" />
                                <div class="flex justify-start items-center p-2 pb-3 pt-3">
                                    <span>表格边框：</span>
                                    <a-switch v-model:checked="state.tableConfig.border" />
                                </div>
                                <a-divider style="margin: 0" />
                                <div class="flex justify-start items-center p-2 pt-3">
                                    <span>紧凑模式：</span>
                                    <a-switch v-model:checked="state.tableConfig.size" />
                                </div>
                            </a-tab-pane>
                            <template #rightExtra>
                                <a-tooltip>
                                    <template #title>恢复默认配置</template>
                                    <sysIcon style="font-size: 20px" type="system-shuazi" class="link mr-2 text-gray-600" @click="reset" />
                                </a-tooltip>
                            </template>
                        </a-tabs>
                    </div>
                </template>
            </vxe-pulldown>
            <sysIcon class="link text-gery-500" type="system-quanping" @click="zoomEvent" style="font-size: 17px; font-weight: bold"></sysIcon>
        </a-space>
    </div>
</template>
<script setup>
const emits = defineEmits(['change', 'update:value'])
const props = defineProps({
    xGrid: null,
    gridOptions: {
        type: Object,
    },
})

const state = reactive({
    xGrid2: undefined,
    tGrid: undefined,
    zoom: false,
    visible2: false,
    columnsOld: null,
    activeKey: '1',

    //拖拽
    sortable: undefined,
    tableData: [],
    //风格
    tableConfig: {},

    store: useStore(),
})

//表格行的拖拽
const rowDrop = () => {
    state.sortable = Sortable.create(state.tGrid.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
        handle: '.drag-btn',
        onEnd: sortableEvent => {
            const newIndex = sortableEvent.newIndex
            const oldIndex = sortableEvent.oldIndex
            const currRow = state.tableData.splice(oldIndex, 1)[0]
            state.tableData.splice(newIndex, 0, currRow)
            changeTable()
        },
    })
}

function openMorePanel() {
    setTimeout(() => {
        rowDrop()
    }, 300)
    clearClumn()
}
function closePulldown() {
    if (state.sortable) {
        state.sortable.destroy()
    }
}

setTimeout(() => {
    getStorageColumn()
}, 50)

//清除无关列数据，包括checkbox，radio,operate
function clearClumn() {
    state.tableData = []
    props.gridOptions.columns.forEach(element => {
        if (element.type !== 'checkbox' && element.type !== 'radio' && element.title !== '操作' && element.type !== '') {
            state.tableData.push(element)
        }
    })
}
//追加无关列数据，包括checkbox，radio,operate
function addClumn() {
    let newArr = []
    state.tableData.forEach(element => {
        newArr.push(element)
    })
    props.gridOptions.columns.forEach(element => {
        if (element.type === 'checkbox' || element.type === 'radio') {
            newArr.unshift(element)
        }
        if (element.field === 'operate') {
            newArr.push(element)
        }
    })
    return newArr
}

//重置列
const reset = () => {
    //列
    localStorage.removeItem('VXE_TABLE_CUSTOM_COLUMN_WIDTH')
    let storeData = useStore().table.tableColumn
    let index = getIndex({
        datas: storeData,
        name: 'key',
        value: props.xGrid.id,
    })
    props.gridOptions.columns = cloneParse(storeData[index].oldData)
    storeData[index].data = storeData[index].oldData
    useStore().table.tableColumn = storeData
    message.success('已恢复到默认状态')
    state.xGrid2.togglePanel()
    //初始化风格
    state.tableConfig.stripe = false
    state.tableConfig.size = false
    state.tableConfig.border = false
}

//客户端改变配置，存入缓存
function changeTable() {
    let storeData = useStore().table.tableColumn
    let index = getIndex({
        datas: storeData,
        name: 'key',
        value: props.xGrid.id,
    })
    let newData = addClumn()
    props.gridOptions.columns = []
    props.gridOptions.columns = newData
    storeData[index].data = cloneString(props.gridOptions.columns)
    useStore().table.tableColumn = storeData
}

//进入页面后查询数据
const getStorageColumn = () => {
    if (!props.gridOptions.columns.length) return
    let storeData = useStore().table.tableColumn
    let index = getIndex({
        datas: storeData,
        name: 'key',
        value: props.xGrid.id,
    })
    /* 
    1：判断缓存是否存在列数据（true）
    */
    if (index !== undefined) {
        //判断列数据是否为代码改动（false）
        if (storeData[index].oldData === cloneString(props.gridOptions.columns)) {
            //判断列数据的配置是否被用户自定义（true）
            if (storeData[index].data !== cloneString(props.gridOptions.columns)) {
                props.gridOptions.columns = cloneParse(storeData[index].data)
            }
        } else {
            //代码改动，更新缓存
            storeData[index] = {
                key: props.xGrid.id,
                data: cloneString(props.gridOptions.columns),
                oldData: cloneString(props.gridOptions.columns),
            }
            useStore().table.tableColumn = storeData
        }
    } else {
        //首次存入缓存
        storeData.push({
            key: props.xGrid.id,
            data: cloneString(props.gridOptions.columns),
            oldData: cloneString(props.gridOptions.columns),
        })
        useStore().table.tableColumn = storeData
    }
}

//转str存储
function cloneString(jsonData) {
    let str = JSON.stringify(jsonData, function (key, val) {
        if (key == 'formatter') {
            return val.toString()
        }
        return val
    })
    return str
}
//拼接相关函数
function cloneParse(strData) {
    let newArr = JSON.parse(strData)
    let newArr2 = XEUtils.clone(props.gridOptions.columns)
    newArr.forEach((element, index) => {
        newArr2.forEach((element2, index2) => {
            if (element.formatter && element.field === element2.field) {
                newArr[index].formatter = newArr2[index2].formatter
            }
        })
    })
    return newArr
}

//设置表格全屏
const zoomEvent = () => {
    props.xGrid.zoom()
    state.zoom = props.xGrid.isMaximized()
}

//读取缓存配置（风格）
state.tableConfig = useStore().table.tableConfig
setProps(state.tableConfig)
//设置表格
function setProps(newVal) {
    props.gridOptions.stripe = newVal.stripe
    if (newVal.size) {
        props.gridOptions.size = 'mini'
        props.gridOptions.rowConfig.height = 45
    } else {
        props.gridOptions.size = 'medium'
        props.gridOptions.rowConfig.height = 55
    }
    if (newVal.border) {
        props.gridOptions.border = 'full'
    } else {
        props.gridOptions.border = 'inner'
    }
}
watch(
    () => state.tableConfig,
    (newVal, oldVal) => {
        useStore().table.tableConfig = {
            stripe: newVal.stripe,
            size: newVal.size,
            border: newVal.border,
        }
        setProps(newVal)
    },
    { deep: true }
)

watch(
    () => state.store.table.tableConfig.size,
    (newVal, oldVal) => {
        if (newVal) {
            props.gridOptions.size = 'mini'
            props.gridOptions.rowConfig.height = 45
        } else {
            props.gridOptions.size = 'medium'
            props.gridOptions.rowConfig.height = 55
        }
    },
    { deep: true }
)

const { xGrid } = toRefs(props)
const { xGrid2, tGrid, zoom, visible2, activeKey } = toRefs(state)
</script>
<style>
.my_menu_column li {
    padding-top: 0;
    padding-bottom: 0;
    line-height: 30px;
}
.sortable-row-demo .drag-btn {
    cursor: move;
    font-size: 12px;
}
.sortable-row-demo .vxe-body--row.sortable-ghost,
.sortable-row-demo .vxe-body--row.sortable-chosen {
    background-color: #dfecfb;
}
</style>
